GROUP_URL = "https://groups.google.com/a/{ SITE }/group/{ GROUP }/"
SETTINGS_URL = GROUP_URL + "manage_access"
MEMBERS_URL = GROUP_URL + "members"
SITE = null;
function setSite(site) {
    SITE = site;
    GROUP_URL = GROUP_URL.replace( /{\s*SITE\s*}/g, SITE );
    SETTINGS_URL = SETTINGS_URL.replace( /{\s*SITE\s*}/g, SITE );
    MEMBERS_URL = MEMBERS_URL.replace( /{\s*SITE\s*}/g, SITE );
}

function buildGroupRow(group_data) {
    group_data=group_data[0];
    var groupId = cleanId( group_data['groupId']);
    var tr = $(jQuery( '<tr>'))
	.addClass('GoogleGroupsWebUI_row')
	.attr('id', groupId +"_row")
	.append($(jQuery('<td>'))
		.addClass('GoogleGroupsWebUI_status_cell')
		.html(statusIcon('unloaded'))
		.click(function() {forceReload(group_data['groupId'])}))
	.append($(jQuery('<td>'))
		.addClass('GoogleGroupsWebUI_name_cell')
		.html(group_data['groupName'])
		.click(function() {expandGroupRow(groupId)}))
	.append($(jQuery('<td>'))
		.addClass('GoogleGroupsWebUI_id_cell')
		.html(group_data['groupId'])
		.click(function() {expandGroupRow(groupId)}))
	.append($(jQuery('<td>'))
		.addClass('GoogleGroupsWebUI_permission_cell')
		.html(group_data['emailPermission'])
		.click(function() {expandGroupRow(groupId)}))
	.append($(jQuery('<td>'))
		.addClass('GoogleGroupsWebUI_owner_count_cell')
		.html('-')
		.attr('id', groupId + "_owner_count")
		.click(function() {expandGroupRow(groupId)}))
	.append($(jQuery('<td>'))
		.addClass('GoogleGroupsWebUI_member_count_cell')
		.html( '-')
		.attr('id', groupId + "_member_count")
		.click(function() {expandGroupRow(groupId)}))
	.append($(jQuery('<td>'))
		.addClass('GoogleGroupsWebUI_link_cell')
		.append(groupLinks(group_data)))
	.after(	$(jQuery('<tr>'))
		.attr( 'name', groupId + "_description")
		.attr( 'class', "GoogleGroupsWebUI_infoRow")
		.append($(jQuery('<td>'))
			.attr('colspan', 2)
			.addClass('GoogleGroupsWebUI_infoHeader')
			.append("Description"))
		.append($(jQuery("<td>"))
			.attr('colspan', 5)
			.addClass('GoogleGroupsWebUI_info')
			.append(group_data['description']))
		.hide()
	      );
    return [tr];
}
GROUP_DATA = [];
function putRows() {
    var tbody = $('#GoogleGroupsWebUI_table_rows');
    var even = false;
    $.each(GROUP_DATA, function() {
	var row = $('#' + this['id'] + '_row');
	if( even ) {
	    row.removeClass("GoogleGroupsWebUI_odd");
	    row.addClass("GoogleGroupsWebUI_even");
	} else { 
	    row.removeClass("GoogleGroupsWebUI_even");
	    row.addClass("GoogleGroupsWebUI_odd");
	}
	even = ! even;
	tbody.append(row);
	tbody.append($('[name=' + this['id'] + '_description]'));
	tbody.append($('[name=' + this['id'] + '_info]'));
    });
}


function addRows() {
    var tbody = $('#GoogleGroupsWebUI_table_rows');
    var even = false;
    $.each(GROUP_LIST, function() {
	var trs = buildGroupRow($(this));
	if( even ) {
	    trs[0].removeClass("GoogleGroupsWebUI_odd");
	    trs[0].addClass("GoogleGroupsWebUI_even");
	} else { 
	    trs[0].removeClass("GoogleGroupsWebUI_even");
	    trs[0].addClass("GoogleGroupsWebUI_odd");
	}
	even = ! even;
	$.each( trs, function () {
	    this.appendTo(tbody);
	});

	GROUP_DATA.push( { id: cleanId(this['groupId']),
			   name: this['groupName'],
			   permission: this['emailPermission'],
			 } );
	$.ajax({ url: "/" + SITE + "/users/" + this['groupId'],
		 dataType: "json",
		 success: buildGroupDetailRows,
		 'error': function () { failedGroupDetailLoad(this['groupId']) },
	       });

    });
}

oldby = "";
function sortTable(by) {
    if( ! by ) by = "name";
    GROUP_DATA.sort( function (a,b) {
	a=a[by];
	b=b[by];
	if( a < b ) return -1;
	else if (a > b ) return 1;
	else return 0;
    });

    $("span[name=arrow]").html("&rarr;");
    var arrow = $("#GoogleGroupsWebUI_by_" + by);
    if( by == oldby ) { 
	arrow.html("&uarr;");
	GROUP_DATA.reverse();
	oldby = "";
    } else {
	arrow.html("&darr;");
	oldby = by;
    }
    putRows();
}

function forceReload(groupId) {
    cGroupId = cleanId(groupId);
    $("#" + cGroupId + "_row > td[class=GoogleGroupsWebUI_status_cell]")
	.html(statusIcon("unloaded"));
    $.ajax({ url: "/" + SITE + "/users/" + groupId,
	     data: { force: true},
	     dataType: "json",
	     success: buildGroupDetailRows,
	     'error': function () { failedGroupDetailLoad(groupId) },
 });
}

function failedGroupDetailLoad(groupId) {
    cGroupId = cleanId(groupId);
    $("#" + cGroupId + "_row > td[class=GoogleGroupsWebUI_status_cell]")
	.empty()
	.append(statusIcon("failed"));
}

function statusIcon(status) {
    if( status == "unloaded") {
	return "&olarr;";
    } else if( status== "loaded") {
	return "&#10004;";
    } else if( status== "failed") {
	return "X";
	return $(jQuery("<span>"))
	    .addClass( 'GoogleGroupsWebUI_error' )
	    .append("X");
    }
}
function groupLinks(group_data) {
    group_id = group_data['groupId'].replace(/@.*$/,'')
    group_url = GROUP_URL.replace( /\{\s*GROUP\s*\}/g, group_id );
    settings_url = SETTINGS_URL.replace( /{\s*GROUP\s*}/g, group_id );
    members_url = MEMBERS_URL.replace( /{\s*GROUP\s*}/g, group_id );


    return $(jQuery("<a>"))
	.attr('href', group_url)
	.attr('target', '_top')
	.append("Group")
	.after("<span>&nbsp;</span>")
	.after($(jQuery("<a>"))
	       .attr('href', settings_url)
	       .attr('target', '_top')
	       .append("Settings"))
	.after("<span>&nbsp;</span>")
    	.after($(jQuery("<a>"))
	       .attr('href', members_url)
	       .attr('target', '_top')
	       .append("Members"));
}

function cleanId(id) {
    return id.replace(/[@\.]/g, "_");
}

var showInfo = {};
function expandGroupRow(id) {
    // If unset, then default to true
    var showOrHide = ! showInfo[id];

    $('.GoogleGroupsWebUI_row').removeClass("GoogleGroupsWebUI_highlighted");
    $('.GoogleGroupsWebUI_infoRow').hide();
    for( _id in showInfo ) showInfo[_id] = false;

    if( showOrHide ) {
	$('#' + id + '_row').addClass("GoogleGroupsWebUI_highlighted");
	$('[name=' + id + '_description]').removeClass('GoogleGroupsWebUI_even').removeClass('GoogleGroupsWebUI_odd').show();
	$('[name=' + id + '_description]').removeClass('GoogleGroupsWebUI_even').removeClass('GoogleGroupsWebUI_odd').show();
	$('[name=' + id + '_info]').show();
    }
    showInfo[id] = showOrHide;
}

function hideGroupInfo(id) {
    $('[name=' + id + '_description]').hide();
    $('[name=' + id + '_info]').hide();
}

function showGroupInfo(id) {
    // Only show if set to be shown
    if( showInfo[id] ) {
	$('[name=' + id + '_description]').show();
	$('[name=' + id + '_info]').show();
    }
}

function filter(input,type) {
    var txt = input.value;
    var cells;
    if( type == "name" )
        cells =  $("td[class=GoogleGroupsWebUI_name_cell]")
    else if( type == "id" )
        cells =  $("td[class=GoogleGroupsWebUI_id_cell]")
    else if( type == "permission" )
        cells =  $("td[class=GoogleGroupsWebUI_permission_cell]")

    even = false;
    $.each(cells, function() {
	var row = $(this).parent();
	var groupId = $(row).attr("id").replace(/_row$/, "");
        if( txt == "" || $(this).html().toLowerCase().indexOf(txt.toLowerCase()) != -1 ){
	    if( even ) {
		row.removeClass("GoogleGroupsWebUI_odd");
		row.addClass("GoogleGroupsWebUI_even");
	    } else { 
		row.removeClass("GoogleGroupsWebUI_even");
		row.addClass("GoogleGroupsWebUI_odd");
	    }
	    even = ! even;

	    row.show();
	    showGroupInfo(groupId);
        } else {
            row.hide();
	    hideGroupInfo(groupId);
	}
    });
}

function buildGroupDetailRows(group_data) {
    var group_name = cleanId(group_data['groupName']);
    var member_count_cell_id = "#" + group_name + "_member_count";
    var owner_count_cell_id = "#" + group_name + "_owner_count";
    $(member_count_cell_id).html(group_data['members']['data'].length);
    $(owner_count_cell_id).html(group_data['owners']['data'].length);
    var members = [];
    $.each(group_data['members']['data'], function() {
	members.push(this['memberId'].replace("@" + SITE, ""));
    }); 
    var owners = [];
    $.each(group_data['owners']['data'], function() {
	owners.push( this['email'].replace("@" + SITE, ""));
    });
    var data_record;
    $.each(GROUP_DATA, function() {
	if( this['id'] == group_name ) {
	    data_record = this;
	    this['owners'] = owners.length;
	    this['members'] = members.length;
	}});
    // Clear previous data
    $("tr[name=" + group_name + "_info]").remove();

    $("tr[name=" + group_name + "_description]")
	.after($(jQuery('<tr>'))
	       .attr('name', group_name + "_info")
	       .attr('class', 'GoogleGroupsWebUI_infoRow')
	       .append($(jQuery('<td>'))
		       .attr('colspan', 2)
		       .addClass('GoogleGroupsWebUI_infoHeader')
		       .append("Members"))
	       .append($(jQuery("<td>"))
		       .attr('colspan', 5)
		       .addClass('GoogleGroupsWebUI_info')
		       .append(members.join(", ") || "none"))
	       .hide())
	.after($(jQuery('<tr>'))
	       .attr('name', group_name + "_info")
	       .attr('class', 'GoogleGroupsWebUI_infoRow')
	       .append($(jQuery('<td>'))
		       .attr('colspan', 2)
		       .addClass('GoogleGroupsWebUI_infoHeader')
		       .append("Owners"))
	       .append($(jQuery("<td>"))
		       .attr('colspan', 5)
		       .addClass('GoogleGroupsWebUI_info')
		       .append(owners.join(", ") || "none"))
	       .hide());

    $("#" + group_name + "_row > td[class=GoogleGroupsWebUI_status_cell]")
	.html(statusIcon("loaded"));
    showGroupInfo(group_name);
}
 